<template>
  <div>
    <h2>在文本域光标位置插入文本</h2>
    
    <div>
      <el-input
        ref="textareaRef"
        type="textarea"
        :modelValue="textareaContent"
        @input="handleInput"
        @click="handleClick"
        @keyup="handleKeyup"
        :rows="5"
        placeholder="我是优秀的人"
      />
    </div>
    
    <div v-if="cursorPosition >= 0">
      当前光标位置: {{ cursorPosition }}
    </div>
    
    <div>
      <button @click="insertText('帅气的')">插入"帅气的"</button>
      <button @click="insertText('聪明的')">插入"聪明的"</button>
      <button @click="insertText('努力的')">插入"努力的"</button>
      <button @click="insertText('优秀的')">插入"优秀的"</button>
    </div>
    
    <div>
      <input 
        v-model="customText" 
        placeholder="输入自定义文本"
        @keyup.enter="insertCustomText"
      >
      <button @click="insertCustomText">插入自定义文本</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

const textareaContent = ref('我是优秀的人')
const cursorPosition = ref(-1)
const customText = ref('')
const textareaRef = ref(null)

// 保存光标位置
const saveCursorPosition = () => {
  if (textareaRef.value) {
    // 获取el-input内部的textarea元素
    const textarea = textareaRef.value.$el.querySelector('textarea')
    if (textarea) {
      cursorPosition.value = textarea.selectionStart
    }
  }
}

const handleInput = (value) => {
  textareaContent.value = value
  nextTick(() => {
    saveCursorPosition()
  })
}

const handleClick = () => {
  nextTick(() => {
    saveCursorPosition()
  })
}

const handleKeyup = () => {
  nextTick(() => {
    saveCursorPosition()
  })
}

const insertText = (text) => {
  if (cursorPosition.value < 0) {
    alert('请先在文本域中点击确定光标位置')
    return
  }
  
  const before = textareaContent.value.substring(0, cursorPosition.value)
  const after = textareaContent.value.substring(cursorPosition.value)
  textareaContent.value = before + text + after
  
  nextTick(() => {
    const newPosition = cursorPosition.value + text.length
    setCursorPosition(newPosition)
    cursorPosition.value = newPosition
  })
}

const insertCustomText = () => {
  if (!customText.value) {
    alert('请输入要插入的文本')
    return
  }
  insertText(customText.value)
  customText.value = ''
}

const setCursorPosition = (position) => {
  nextTick(() => {
    if (textareaRef.value) {
      const textarea = textareaRef.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.focus()
        textarea.setSelectionRange(position, position)
      }
    }
  })
}

onMounted(() => {
  // 初始设置光标位置
  nextTick(() => {
    if (textareaRef.value) {
      const textarea = textareaRef.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.focus()
        cursorPosition.value = textarea.selectionStart
      }
    }
  })
})
</script>